const { Router } = require("express");
const router = new Router();
const middleware_resource = require("../../middleware/resource");
const middleware_limiWeb = require("../../middleware/limitWeb");
const assert = require("http-assert");
const { resData } = require("../../utils/format");
const commodityModel = require("../../models/Commodity");
const homeServer = require("./home/index");
const orderServer = require("./order/index");
const order = require("./order/index");
module.exports = app => {
    router.get("/list", async (req, res) => {
        let { page = 1, pageSize = 10 } = req.query;
        page = Number(page);
        pageSize = Number(pageSize);
        let queryOptions = {};
        let queryBuilder = {};
        switch (req.commonModel.modelName) {
            case "Commodity":
                const { cat } = req.query;
                queryOptions.populate = "cat";
                cat ? (queryBuilder.cat = cat) : false;
                break;
            case "Category":
                break;
        }
        try {
            const data = await req.commonModel
                .find(queryBuilder)
                .sort({ updateTime: -1 })
                .setOptions(queryOptions)
                .skip(page - 1)
                .limit(pageSize);
            const total = await req.commonModel.find().countDocuments();
            res.send(resData(data, { page, pageSize, total }));
        } catch (err) {
            res.send(resData([], { page, pageSize }));
        }
    });
    app.use("/web/api/rest/:resource", middleware_resource(), middleware_limiWeb(), router);
    homeServer(app);
    orderServer(app);
};
